package stx.com.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import stx.com.entity.TUser;
import stx.com.util.Constans;

@Repository
public class UserDaoImp implements UserDao {
	
	@Resource
	private JdbcTemplate jdbcTemplate;

	/*
	 * (non-Javadoc)
	 * 注册
	 * @see stx.com.dao.UserDao#regist(stx.com.entity.TUser)
	 */
	@Override
	public boolean regist(TUser user) {
		String sql="insert into tbl_user1 values(userid.nextval,?,?,?,?,?)";
		Object[] s = new Object[]{user.getUseraccounts(),user.getPassword(),user.getNickname(),user.getMood(),user.getRoute()};
		int num=jdbcTemplate.update(sql, s);
		return num==1;
	}

	/*
	 * (non-Javadoc)
	 * 登录
	 * @see stx.com.dao.UserDao#login(stx.com.entity.TUser)
	 */
	@Override
	public boolean login(TUser user) {
		String sql="select * from tbl_user1 where useraccounts=? and password=?";
		Object[] args=new Object[]{user.getUseraccounts(),user.getPassword()};
		List<TUser> users =jdbcTemplate.query(sql, args, new MyRowMapper());
		return users.size()==Constans.REYURN_NUM;
	}
	

	/*
	 * (non-Javadoc)
	 * 修改用户信息
	 * @see stx.com.dao.UserDao#update(stx.com.entity.TUser)
	 */
	@Override
	public boolean update(TUser user) {
		String sql="update tbl_user1 set nickname=?,mood=?,route=? where useraccounts=?";
		Object[] args=new Object[] {user.getNickname(),user.getMood(),user.getRoute(),user.getUseraccounts()};
		return jdbcTemplate.update(sql, args)==Constans.REYURN_NUM;
	}

	/*
	 * (non-Javadoc)
	 * 查看用户信息
	 * @see stx.com.dao.UserDao#check(stx.com.entity.TUser)
	 */
	@Override
	public TUser check(TUser user) {
		String sql="select * from tbl_user1 where useraccounts=?";
		Object[] args=new Object[] {user.getUseraccounts()};
		List<TUser> users=jdbcTemplate.query(sql, args,new MyRowMapper());
		return users.get(0);
	}
	
	private class MyRowMapper implements RowMapper {
		@Override
		public TUser mapRow(ResultSet rs, int arg1) throws SQLException {
			TUser user = new TUser();
			user.setUseraccounts(rs.getString("useraccounts"));
			user.setPassword(rs.getString("password"));
			user.setNickname(rs.getString("nickname"));
			user.setMood(rs.getString("mood"));
			user.setRoute(rs.getString("route"));
			return user;
		}
	}

}
